<?php

namespace App\HttpController\Api;

use App\HttpController\BaseController;
use App\Model\AppPlatformModel;
use App\Model\MessageModel;
use App\Model\GroupMessageModel;
use App\Model\GroupMessageReadModel;
use App\Model\GroupModel;
use App\Model\GroupUserModel;
use App\Model\UserModel;
use App\Model\AppMemberModel;
use App\Model\AppSellerModel;
use App\Model\ApplicationModel;
use App\Resources\RedisResources;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use App\HttpController\Api\Message;



class Group extends BaseController {
    public $imgDomain = 'http://cdn.zczmer.com';
    public function createGroup() {
        $time = time();
        $userId = $this->request()->getRequestParam('user_id');
        $memberIds = $this->request()->getRequestParam('member_ids');
        $memberIdsArr = explode(',', $memberIds);
        $members = UserModel::create()->where('id', $memberIdsArr, 'in')->select();
        try {
            // 启动事务
            DbManager::getInstance()->startTransaction();

            $group = [
                'group_name' => implode(',', array_column($members, 'name')),
                'user_id' => $userId,
                'add_time' => $time
            ];
            $group_id = GroupModel::create($group)->save();
            $group_user = [];
            if ($group_id) {
                foreach ($members as $v) {

                    $group_user = [
                        'group_id' => $group_id,
                        'user_id' => $v['id'],
                        'user_name' => $v['name'],
                        'img' => $v['img'],
                        'add_time' => $time,
                        'nickname' => '',
                        'master_flag' => $userId == $v['id'] ? 1 : 0,
                    ];
                    GroupUserModel::create($group_user)->save();
                }
            }
            // 提交事务
            DbManager::getInstance()->commit();
        } catch (\Throwable $throwable) {
            // 回滚事务
            DbManager::getInstance()->rollback();
            $this->writeJson(400, '', $throwable);
        }
        $group = GroupModel::create()->where(['id' => $group_id])->findOne();
        $this->writeJson(200, '消息列表', ['user_id' => $userId, 'group' => $group, 'member' => $members]);
    }

    public function groupUserList() {
        $group_id = $this->request()->getRequestParam('group_id');
        $data = GroupUserModel::create()->where(['group_id' => $group_id])->order('master_flag', 'desc')->select();

        $this->writeJson(200, '成员列表', $data);
    }

    public function groupInfo() {
        $group_id = $this->request()->getRequestParam('group_id');
        $user_id = $this->request()->getRequestParam('user_id');

        $queryBuild = new QueryBuilder();
        $sql = "select a.*,b.group_name from ty_group_user as a join ty_group b on b.id=a.group_id where a.group_id={$group_id} and a.user_id={$user_id}";
        $queryBuild->raw($sql);
        $info = DbManager::getInstance()->query($queryBuild, true)->getResult();

        $this->writeJson(200, '群聊详情', $info[0]);
    }

    public function editGroup() {
        $edit_type = $this->request()->getRequestParam('edit_type');
        $user_id = $this->request()->getRequestParam('user_id');
        $group_id = $this->request()->getRequestParam('group_id');
        $keyword = $this->request()->getRequestParam('keyword');
        switch ($edit_type) {
            case 'edit_name':
                $res = GroupModel::create()->where(['id' => $group_id])->update(['group_name' => $keyword]);
                break;
            case 'set_group_nickname':
                $res = GroupUserModel::create()->where(['group_id' => $group_id, 'user_id' => $user_id])->update(['group_nickname' => $keyword]);
                break;
            case 'set_nickname':
                $res = GroupUserModel::create()->where(['group_id' => $group_id, 'user_id' => $user_id])->update(['
                ' => $keyword]);
                break;
            case 'set_remind':
                $res = GroupUserModel::create()->where(['group_id' => $group_id, 'user_id' => $user_id])->update(['remind_flag' => $keyword]);
                break;
            default:
                $res = false;
                break;
        }
        if ($res) {
            if ($res) {
                $message = new Message();
                if ($edit_type == 'edit_name') {

                    $members = GroupUserModel::create()->where("group_id={$group_id}")->select();
                    foreach ($members as $v) {
                        $message->setGroupEmptyRedis($v['user_id']);
                    }
                }
                if ($edit_type == 'set_group_nickname') {
                    $message->setGroupEmptyRedis($user_id);
                }
            }
            $this->writeJson(1, '操作成功');
        } else {
            $this->writeJson(0, '操作失败', $res);
        }
    }

    public function editGroupUser() {
        $edit_type = $this->request()->getRequestParam('edit_type');
        $user_id = $this->request()->getRequestParam('user_id');
        $group_id = $this->request()->getRequestParam('group_id');
        $memberIds = $this->request()->getRequestParam('member_ids');
        $time = time();
        $res = '';
        try {
            // 启动事务
            DbManager::getInstance()->startTransaction();
            switch ($edit_type) {
                case 'add':
                    $memberIdsArr = explode(',', $memberIds);
                    $members = UserModel::create()->where('id', $memberIdsArr, 'in')->select();
                    foreach ($members as $v) {
                        $group_user = [
                            'group_id' => $group_id,
                            'user_id' => $v['id'],
                            'user_name' => $v['name'],
                            'img' => $v['img'],
                            'add_time' => $time,
                            'nickname' => '',
                            'master_flag' => 0,
                        ];
                        GroupUserModel::create($group_user)->save();
                    }
                    break;
                case 'del':
                    $GroupUserModel = new GroupUserModel();
                    $res1 = $GroupUserModel->destroy(['group_id' => $group_id, 'user_id' => $user_id]);
                    $GroupMessageModel = new GroupMessageModel();
                    $res2 = $GroupMessageModel->destroy(['group_id' => $group_id, 'user_id' => $user_id]);
                    $GroupMessageReadModel = new GroupMessageReadModel();
                    $res3 = $GroupMessageReadModel->destroy(['group_id' => $group_id, 'user_id' => $user_id]);

                    $message = new Message();
                    $message->delGroupChatList($user_id, $group_id);
            }

            // 提交事务
            DbManager::getInstance()->commit();
        } catch (\Throwable $throwable) {
            // 回滚事务
            DbManager::getInstance()->rollback();
            $this->writeJson(0, '', $throwable);
        }
        $this->writeJson(1, '操作成员成功', $res);
    }

    /**
     * 发送通知
     * @param $data
     * @return void
     */
    public function sendNotice($data) {
        //处理通知
        $info = [];
        $from = UserModel::create()->where("id = " . $data['from_id'])->findOne();
        $send = UserModel::create()->where("id = " . $data['send_id'])->findOne();
        $appMember = AppMemberModel::create()->where("id = " . $from['user_id'])->findOne();
        $appPlatform = AppPlatformModel::create()->where('id = ' . $send['platform_id'])->findOne();
        $store_name = '';
        $template_id = $appPlatform['msg_template_id']; //微信模板id

        if ($from['platform_id'] == 3) {

            $appMemberUserId = $appMember['id'];
            if ($appMember['pid'] != 0) {
                $parentAppMember = AppMemberModel::create()->where("id = " . $appMember['pid'])->findOne();
                $appMemberUserId = $parentAppMember['id'];
            }

            $appSeller = AppSellerModel::create()->where("pid = {$send['platform_id']} and mid = " . $appMemberUserId)->findOne();
            $store_name = $appSeller['store_name'];
            $nick_name = $appMember['title'];
        } else {
            $nick_name = $from['name'];
        }

        // $sendAppMember['cid'] = '';


        // if($send['platform_id'] == 3){
        //     $sendAppMember = AppMemberModel::create()->where("id = ".$send['user_id'])->findOne();
        // }

        $info['send']  = ['open_id' => $send['open_id'], 'cid' => $send['cid']];
        $info['from']  = ['nick_name' => $nick_name, 'store_name' => $store_name];
        if ($data['msg_type'] == 2) {
            $data['content'] = '[图片]';
        } elseif ($data['msg_type'] == 4) {
            $data['content'] = '[语音]';
        } elseif ($data['msg_type'] == 5) {
            $data['content'] = '[视频]';
        } else {
            $data['content'] = $data['content'];
        }

        //$data['content'] = $data['msg_type'] == 2 ? '[图片]':($data['msg_type'] == 4 ? '[语音]' : $data['content']);

        if ($template_id && $info['send']['open_id']) {
            $wx_param['type'] = 'msg';
            $wx_param['store_name'] = $info['from']['store_name'];
            $wx_param['nick_name'] = $info['from']['nick_name'];
            $wx_param['open_id'] = $info['send']['open_id'];
            $wx_param['content'] = $data['content'];
            $wx_param['template_id'] = $template_id;
            $wx_param['payload'] = $data['payload'];
            $wx_param['pid'] = $send['platform_id'];
            $url = 'https://shop.zczmer.com/WXAPI/App/sendTemplateMsg';
            $res = $this->httpRequest($url, 'POST', json_encode($wx_param));
            print_r('推送通知返回数据' . json_encode($res) . PHP_EOL);
        }

        if ($info['send']['cid']) {
            $app_param['cids'] = $info['send']['cid'];
            $app_param['title'] = $info['from']['store_name'] . $info['from']['nick_name'];
            $app_param['content'] = $data['content'];
            $app_param['payload'] = $data['payload'];
            $url = 'https://shop.zczmer.com/WXAPI/App/sendPush';
            $res = $this->httpRequest($url, 'POST', json_encode($app_param));
            print_r('推送通知返回数据' . json_encode($res) . PHP_EOL);
        }
    }


    /**
     * CURL请求
     * @param $url 请求url地址
     * @param $method 请求方法 get post
     * @param null $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug  调试开启 默认false
     * @return mixed
     */
    public function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {

        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        // if(!empty($postfields['upload'])){
        //     $file = $postfields['upload']['image'];
        //     $filename = $file['name'];
        //     $filepath = $file['tmp_name'];
        //     $filetype = $file['type'];
        //     $postfields = ['upload' => new \CURLFile(realpath($filepath), $filetype, $filename)];
        // }
        // var_dump($postfields);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
        //return array($http_code, $response,$requestinfo);
    }
}
